package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.ws.rs.GET;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/list",name = "展示购销合同列表数据")
    public String findAll(@RequestParam(value ="page",defaultValue = "1") Integer pageNumber, @RequestParam(value ="size",defaultValue = "10")  Integer pageSize){

//        构建根据企业id查询条件
        ContractExample example = new ContractExample();

        example.setOrderByClause("create_time desc");

        ContractExample.Criteria criteria = example.createCriteria().andCompanyIdEqualTo(getCompanyId());//   select * from co_contract where company_id=??

        User user = getUser(); //当前登录人
        Integer degree = user.getDegree();//等级
        //    2-管理所有下属部门和人员   部门总经理
        //  3-管理本部门     部门经理
        //  4-普通员工
        if(degree==4){  //        销售部北京分部的普通销售员小王  xiaoer 只能看自己添加的数据   and create_by= 当前登录人的id
            criteria.andCreateByEqualTo(user.getId());
        }else if(degree==3){ //        销售部北京分部部门经理 dawang  能看自己的并且能看自己部门的所有数据  and create_dept = 当前登录人的部门id
            criteria.andCreateDeptEqualTo(user.getDeptId()); // 注意这里不要写成 user.getCreateDept()
        } else if(degree==2){
            criteria.andCreateDeptLike(user.getDeptId()+"%"); // 销售总部 总经理dalaowang 能看自己所有的下属部门的数据
        }

        PageInfo pageInfo = contractService.findAll(example, pageNumber, pageSize);

        request.setAttribute("page",pageInfo);

        return "cargo/contract/contract-list";
    }


    @RequestMapping(value = "/toAdd",name = "进入到新增购销合同页面")
    public String toAdd(){

        return "cargo/contract/contract-add";
    }


    @RequestMapping(value = "/toUpdate",name = "进入到修改购销合同页面")
    public String toUpdate(String id){
        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);
        return "cargo/contract/contract-add";
    }


    @RequestMapping(value = "/edit" ,name = "保存购销合同数据")
    public String edit(Contract contract){

        if(StringUtils.isEmpty(contract.getId())){
            contract.setId(UUID.randomUUID().toString());
            contract.setCompanyId(getCompanyId());
            contract.setCompanyName(getCompanyName());
            contract.setState(0); //草稿状态

            contract.setCreateBy(getUser().getId());
            contract.setCreateDept(getUser().getDeptId());
            contractService.save(contract);
        }else {
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/delete" ,name = "删除购销合同数据")
    public String delete(String id){
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/print" ,name = "进入到出货表打印页面")
    public String print(){
        return "/cargo/print/contract-print";
    }


    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/printExcel" ,name = "导出出货表")
    public void printExcel(String inputDate) throws Exception{
//        1、查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());

//        创建一个空的工作薄
        Workbook workbook = new XSSFWorkbook();
//        创建一个空的工作表
        Sheet sheet = workbook.createSheet("出货数据");

        //        设置sheet的列宽
        sheet.setColumnWidth(0,4200); //
        sheet.setColumnWidth(1,26*256); //
        sheet.setColumnWidth(2,16*256); //
        sheet.setColumnWidth(3,26*256); //
        sheet.setColumnWidth(4,16*256); //
        sheet.setColumnWidth(5,16*256); //
        sheet.setColumnWidth(6,16*256); //
        sheet.setColumnWidth(7,16*256); //
        sheet.setColumnWidth(8,16*256); //


        Row bigTitleRow = sheet.createRow(0);
        bigTitleRow.setHeightInPoints(36);
//        处理大标题行
        for (int i = 1; i <= 8; i++) {
            Cell cell = bigTitleRow.createCell(i);
            cell.setCellStyle(bigTitle(workbook));
        }
//        合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
//        添加内容  2018-02  2018年2月份出货表   2020-10    2020年10月份出货表
        sheet.getRow(0).getCell(1).setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表 ");

//        处理小标题
//        客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
        Row titleRow = sheet.createRow(1);
        titleRow.setHeightInPoints(26);
        String[] titles = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
//        处理小标题行
        for (int i = 1; i <= 8; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellStyle(title(workbook));
            cell.setCellValue(titles[i-1]);
        }

        int rowIndex = 2;
        Row row = null;
        Cell cell = null;
        for (ContractProductVo contractProductVo : contractProductVoList) {
           row = sheet.createRow(rowIndex);
            row.setHeightInPoints(20);


           cell = row.createCell(1);
           cell.setCellValue(contractProductVo.getCustomName());
           cell.setCellStyle(text(workbook));

           cell = row.createCell(2);
           cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(text(workbook));

           cell = row.createCell(3);
           cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(text(workbook));

           cell = row.createCell(4);
           cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(text(workbook));
//            "工厂","工厂交期","船期","贸易条款"
           cell = row.createCell(5);
           cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(text(workbook));

           cell = row.createCell(6);
           cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format( contractProductVo.getDeliveryPeriod())); //日期
            cell.setCellStyle(text(workbook));

           cell = row.createCell(7);
           cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format( contractProductVo.getShipTime()));   //日期
            cell.setCellStyle(text(workbook));

           cell = row.createCell(8);
           cell.setCellValue(contractProductVo.getTradeTerms());
            cell.setCellStyle(text(workbook));

            rowIndex++;
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);

        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");


    }



    @RequestMapping(value = "/printExcelWithTemplate" ,name = "带模板导出出货表")
    public void printExcelWithTemplate(String inputDate) throws Exception{
//        1、查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());

//        创建一个有内容的工作薄
        String templatePath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        Workbook workbook = new XSSFWorkbook(new FileInputStream(templatePath));

        Sheet sheet = workbook.getSheetAt(0);
//        添加内容  2018-02  2018年2月份出货表   2020-10    2020年10月份出货表
        sheet.getRow(0).getCell(1).setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表 ");


//        获取模板中的8个样式

        CellStyle[] cellStyles = new CellStyle[8];
        Row row = sheet.getRow(2);
        for (int i = 1; i <=8; i++) {
            cellStyles[i-1] = row.getCell(i).getCellStyle();
        }

        int rowIndex = 2;
        Cell cell = null;
        for (ContractProductVo contractProductVo : contractProductVoList) {
            row = sheet.createRow(rowIndex);
            row.setHeightInPoints(20);


            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
            cell.setCellStyle(cellStyles[0]);

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(cellStyles[1]);

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(cellStyles[2]);

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(cellStyles[3]);
//            "工厂","工厂交期","船期","贸易条款"
            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(cellStyles[4]);

            cell = row.createCell(6);
            cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format( contractProductVo.getDeliveryPeriod())); //日期
            cell.setCellStyle(cellStyles[5]);

            cell = row.createCell(7);
            cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format( contractProductVo.getShipTime()));   //日期
            cell.setCellStyle(cellStyles[6]);

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());
            cell.setCellStyle(cellStyles[7]);

            rowIndex++;
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);



        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");


    }



    @RequestMapping(value = "/printExcelMillon" ,name = "导出百万出货表")
    public void printExcelMillon(String inputDate) throws Exception{
//        1、查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());

//        创建一个空的工作薄
        Workbook workbook = new SXSSFWorkbook();
//        创建一个空的工作表

        Sheet sheet = workbook.createSheet("出货数据");

        //        设置sheet的列宽
        sheet.setColumnWidth(0,4200); //
        sheet.setColumnWidth(1,26*256); //
        sheet.setColumnWidth(2,16*256); //
        sheet.setColumnWidth(3,26*256); //
        sheet.setColumnWidth(4,16*256); //
        sheet.setColumnWidth(5,16*256); //
        sheet.setColumnWidth(6,16*256); //
        sheet.setColumnWidth(7,16*256); //
        sheet.setColumnWidth(8,16*256); //


        Row bigTitleRow = sheet.createRow(0);
        bigTitleRow.setHeightInPoints(36);
//        处理大标题行
        for (int i = 1; i <= 8; i++) {
            Cell cell = bigTitleRow.createCell(i);
            cell.setCellStyle(bigTitle(workbook));
        }
//        合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
//        添加内容  2018-02  2018年2月份出货表   2020-10    2020年10月份出货表
        sheet.getRow(0).getCell(1).setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表 ");

//        处理小标题
//        客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
        Row titleRow = sheet.createRow(1);
        titleRow.setHeightInPoints(26);
        String[] titles = new String[]{"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
//        处理小标题行
        for (int i = 1; i <= 8; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellStyle(title(workbook));
            cell.setCellValue(titles[i-1]);
        }

        int rowIndex = 2;
        Row row = null;
        Cell cell = null;
        for (ContractProductVo contractProductVo : contractProductVoList) {
            for (int i = 0; i < 6060; i++) {
            row = sheet.createRow(rowIndex);
            row.setHeightInPoints(20);

            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
//            cell.setCellStyle(text(workbook));
//            "工厂","工厂交期","船期","贸易条款"
            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(6);
            cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format( contractProductVo.getDeliveryPeriod())); //日期
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(7);
            cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd").format( contractProductVo.getShipTime()));   //日期
//            cell.setCellStyle(text(workbook));

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());
//            cell.setCellStyle(text(workbook));
            rowIndex++;
            }
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);

        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");


    }


    @RequestMapping(value = "/printExcelWithEasyExcel" ,name = "使用EasyExcel导出出货表")
    public void printExcelWithEasyExcel(String inputDate) throws Exception{
        //        1、查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());
        String returnName = "出货表.xlsx";
        response.setContentType("application/octet-stream;charset=utf-8"); //mime类型
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));			//保存的文件名,必须和页面编码一致,否则乱码
        response.addHeader("Content-Disposition",   "attachment;filename=" + returnName); //文件的打开方式
        EasyExcel.write(response.getOutputStream()).head(ContractProductVo.class)
                .sheet("sheet的名字").doWrite(contractProductVoList);
    }



    @RequestMapping(value = "/printExcelWithEasyExcelAndTemplate" ,name = "使用EasyExcel借助模板导出出货表")
    public void printExcelWithEasyExcelAndTemplate(String inputDate) throws Exception{
        //        1、查询数据
        List<ContractProductVo> contractProductVoList = contractService.findContractProductVoListByShipTime(inputDate,getCompanyId());
        String returnName = "出货表.xlsx";
        response.setContentType("application/octet-stream;charset=utf-8"); //mime类型
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));			//保存的文件名,必须和页面编码一致,否则乱码
        response.addHeader("Content-Disposition",   "attachment;filename=" + returnName); //文件的打开方式

        String templatePath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT2.xlsx");

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(new FileInputStream(templatePath)).head(ContractProductVo.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("sheet的名字").build();
        excelWriter.fill(contractProductVoList,writeSheet);

        Map map = new HashMap();
        map.put("time",inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表 ");
        excelWriter.fill(map,writeSheet);

        excelWriter.finish();

    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }



    @RequestMapping(value = "/submit" ,name = "提交购销合同")
    public String submit(String id){
//        update co_contract set state =1 where id=?
//        contractService.updateStateById(id);
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);

        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping(value = "/cancel" ,name = "取消提交购销合同")
    public String cancel(String id){
//        update co_contract set state =1 where id=?
//        contractService.updateStateById(id);
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

}
